export interface FlowRateMonitorOptions {
	uploadSpeed: number;
	downloadSpeed: number;
	totalUploadFlow: number;
	totalDownloadFlow: number;
}

type FlowRateMonitorCallback = ({
	uploadSpeed,
	downloadSpeed,
	totalUploadFlow,
	totalDownloadFlow,
}: FlowRateMonitorOptions) => void;

export class FlowRateMonitor {
	totalUploadFlow = 0;
	totalDownloadFlow = 0;
	callback: FlowRateMonitorCallback;

	constructor(callback: FlowRateMonitorCallback) {
		this.callback = callback;
		let lastUploadFlow = 0;
		let lastDownloadFlow = 0;
		setInterval(() => {
			const currentUploadFlow = this.totalUploadFlow - lastUploadFlow;
			const currentDownloadFlow =
				this.totalDownloadFlow - lastDownloadFlow;

			const uploadSpeed =
				Math.round((currentUploadFlow / 1024) * 100) / 100;
			const downloadSpeed =
				Math.round((currentDownloadFlow / 1024) * 100) / 100;
			const totalUploadFlow =
				Math.round((this.totalUploadFlow / 1024) * 100) / 100;
			const totalDownloadFlow =
				Math.round((this.totalDownloadFlow / 1024) * 100) / 100;
			if (
				lastDownloadFlow !== this.totalDownloadFlow ||
				lastUploadFlow !== this.totalUploadFlow
			) {
				this.callback({
					uploadSpeed,
					downloadSpeed,
					totalUploadFlow,
					totalDownloadFlow,
				});
			}
			lastUploadFlow = this.totalUploadFlow;
			lastDownloadFlow = this.totalDownloadFlow;
		}, 1000);
	}
}
